package com.java.distributed.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.java.distributed.beans.CommonResult;
import com.java.distributed.beans.MySession;
import com.java.distributed.beans.User;
import com.java.distributed.service.MySessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.support.WebApplicationContextUtils;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("LoginFilter init Success.........................................");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        if (uri.equals("/login") || uri.equals("/loginV2")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletRequest httpServletRequest =(HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();

        User currentUser = (User) session.getAttribute("currentUser");
        if (null != currentUser) {
            LOGGER.info("当前登录：{}", currentUser);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String domain = this.getDomain(request);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setHeader("redirect", domain+"/login.html");
        CommonResult noLogin = new CommonResult(false, "未登录", null, "S100000002");
        response.getWriter().write(JSON.toJSONString(noLogin));
    }

    @Override
    public void destroy() {

    }

    /**
     * 根据请求获取域名
     *
     * @param httpServletRequest
     * @return
     */
    private  String getDomain(HttpServletRequest httpServletRequest) {
        StringBuffer url = httpServletRequest.getRequestURL();
        String domain = url.delete(url.length() - httpServletRequest.getRequestURI().length(), url.length()).append("/").toString();
        return domain;
    }
}
